package com.zx.jhpt.service;

import com.zx.framework.core.exception.ServiceException;
import com.zx.framework.core.util.DatetimeUtils;
import com.zx.framework.core.util.FileUtil;
import com.zx.framework.core.util.RandomUtil;
import com.zx.framework.db.IBaseDAO;
import com.zx.framework.plat.dept.po.Dept;
import com.zx.framework.plat.user.vo.UserVo;
import com.zx.jhpt.po.Enclosure;
import com.zx.jhpt.po.Replymessage;
import com.zx.jhpt.vo.JhptConts;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Component("enclosureService")
@Transactional
public class EnclosureService {

    private static final Logger LOGGER = Logger.getLogger(EnclosureService.class);
    @Resource
    private IBaseDAO baseDAO;
    @Resource
    private FxfkjzService fxfkjzService;
	@Resource
	private ReplyMessageService replyMessageService;

    public void saveOrUpdate(Enclosure enclosure){
    	baseDAO.saveOrUpdate(enclosure);
    }
    
    public List<Dept> findDeptByOwner(String owner){
    	String hql = "from Dept d where d.owner = ?";
    	return baseDAO.queryHQL(hql, owner);
    }


    public void update(Enclosure enclosure){
    	baseDAO.update(enclosure);
    }
    
    
    public List<Enclosure> getEnclByPkid(String pkid){
    	String hql = "from Enclosure e where e.pkid = ?";
    	return baseDAO.queryHQL(hql, pkid);
    }

	/**
	 * 通过风险ID,部门ID,与稽查文件时间查找唯一一条附件信息
	 * @param fxid 风险ID
	 * @param hcsj 稽查时间
	 * @param deptId 部门ID
	 * @return
	 */
	public Enclosure getEnclosureByFxidAndHcsjAndDept(String fxid,String hcsj,String deptId){
		String hql = "from Enclosure e where e.fxid = ? and to_char(e.hcsj,'yyyy-MM') = ? and e.deptid = ?";
		return baseDAO.getHQLUnique(hql,Enclosure.class,fxid,hcsj,deptId);
	}
    
    public Enclosure findById(String id){
    	return baseDAO.findById(id, Enclosure.class);
    }

    /**
     * 保存回执文件
     * @param mufile
     * @param jhptUpload
     * @param hcsj
     * @param rpid
     * @param loginUser
     */
    public void saveHZ(MultipartFile mufile, String jhptUpload, String hcsj, String rpid, UserVo loginUser) {
        try {
            // 移除旧回执
            baseDAO.executeHQL("delete from Enclosure where pkid=?",rpid);

            Replymessage replymessage = replyMessageService.findById(rpid);

            //保存enclosure
            Enclosure enclosure = new Enclosure();
            enclosure.setId(RandomUtil.getUUID());
            enclosure.setPkid(rpid);
            enclosure.setFilename(mufile.getOriginalFilename());
            enclosure.setHcsj(DatetimeUtils.stringToDate(hcsj, "yyyy-MM"));
            enclosure.setUserid(loginUser.getId());
            enclosure.setUrl(hcsj);
            enclosure.setCreatetime(new Date());
            enclosure.setType(JhptConts.ENCLOSURE_TYPE_HZ);
            enclosure.setFxid(replymessage.getFxid());
            enclosure.setDeptid(replymessage.getDeptid());
            baseDAO.save(enclosure);

            //保存file
            //判断文件目录是否存在
            File dir = new File(jhptUpload + hcsj);
            if(!dir.exists()) {
                //创建文件目录
                FileUtil.createDir(jhptUpload + hcsj);
            }
            String disPath = jhptUpload + hcsj + File.separator + rpid + "." + "enc";
            File file = new File(disPath);
            if(file.exists()){
                FileUtil.deleteQuietly(file);
            }
            file.createNewFile();
            mufile.transferTo(file);
        }catch (Exception e){
            LOGGER.error("回执上传失败:"+e.getMessage(),e);
            throw new ServiceException(e.getMessage());
        }
    }
    
    /**
     * 获取附件
     * @param pkid
     * @param hcsj
     * @param type
     * @param deptid
     * @param fxid
     * @return
     */
    public List<Map> getFujian(Object pkid,Object hcsj,Object type,Object deptid,Object fxid){
    	String hql = "select * from enclosure e where e.pkid = ? and to_char(e.hcsj,'yyyy-MM') = ? and e.type = ? and e.deptid = ? and e.fxid = ?";
    	return baseDAO.querySQL(hql, pkid,hcsj,type,deptid,fxid);
    }
    
    /**
     * 根据核查时间查询所有附件
     * @param hcsj
     * @return
     */
    public List<Map> getEnclByHcsj(String hcsj){
    	String sql = "select e.URL,e.PKID,e.FILENAME,e.FXID,sd.NAME,to_char(e.hcsj,'yyyy-MM') HCSJ "
    			+ "from enclosure e "
    			+ "left join s_dept sd on e.deptid = sd.id "
    			+ "where to_char(e.hcsj,'yyyy-MM') = ?";
    	return baseDAO.querySQL(sql, hcsj);
    }
}
